package com.hcg.multiplydatasourceofanno.config.datasource;

//import org.mybatis.spring.annotation.MapperScan;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置多数据源
 */
@Configuration
@MapperScan(basePackages = "com.hcg.multiplydatasourceofanno.mapper")
public class DynamicDataSourceConfig {

    @Bean
    @Qualifier("cmDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.cm") // 扫描application 配置文件时的前缀
    public DataSource cmDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "hcgDataSource")
    @Qualifier("hcgDataSource") // 依赖注入时候的名字
    @ConfigurationProperties(prefix = "spring.datasource.hcg") // 扫描application 配置文件时的前缀
//    @Primary
    public DataSource hcgDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public AnnoDynamicDataSource dataSource(DataSource hcgDataSource, DataSource cmDataSource) {
        Map<String, DataSource> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceNames.HCG, hcgDataSource);
        targetDataSources.put(DataSourceNames.CM, cmDataSource);
        return new AnnoDynamicDataSource(hcgDataSource, targetDataSources);
    }

    @Bean(name = "transactionManager")
    public DataSourceTransactionManager TransactionManager(DataSource dataSource) throws Exception{
        return new DataSourceTransactionManager(dataSource);
    }

   /* @Bean(name = "cmTransactionManager")
    public DataSourceTransactionManager cmTransactionManager(DataSource cmDataSource) throws Exception{
        return new DataSourceTransactionManager(cmDataSource);
    }

    @Bean(name = "hcgTransactionManager")
    public DataSourceTransactionManager hcgTransactionManager(DataSource hcgDataSource) throws Exception{
        return new DataSourceTransactionManager(hcgDataSource);
    }*/
}

